const service = require("../service/user.service");
const {
  NAME_OR_PASSWORD_IS_REQUIRED,
  NAME_HAS_ALREADY_USED,
  USER_DOES_NOT_EXISTS,
  PASSWORD_IS_WRONG,
  ERROR_TOKEN,
} = require("../constants/errtypes");
const md5password = require("../utils/password-handle");
const jwt = require("jsonwebtoken");
const { PUBLIC_KEY } = require("../app/config");
// 验证登录
const verifyAuth = async (ctx, next) => {
  const { name, password } = ctx.request.body;

  // 1.判断是否为空
  if (!name || !password) {
    return ctx.app.emit("error", new Error(NAME_OR_PASSWORD_IS_REQUIRED), ctx);
  }

  // 2.判断是否注册过
  const result = await service.getUserByName(name);
  //   console.log(result);

  var str = JSON.stringify(result);
  var user = JSON.parse(str)[0];

  // 用户不存在
  if (!user) {
    return ctx.app.emit("error", new Error(USER_DOES_NOT_EXISTS), ctx);
  }
  // 判断加密的密码是否一致
  const passsword2 = md5password(password);

  if (user.password !== passsword2) {
    return ctx.app.emit("error", new Error(PASSWORD_IS_WRONG), ctx);
  }
  ctx.user = user;
  await next();
};

// token验证
const verifySSL = async (ctx, next) => {
  try {
    console.log("验证授权ssl的middleware");
    let token = ctx.request.header.authorization;
    // console.log(token);
    token = token.replace("Bearer ", "");
    //   console.log(token);
    const res = jwt.verify(token, PUBLIC_KEY, {
      algorithms: ["RS256"],
    });
    ctx.user = res;
    // console.log(res);

    await next();
  } catch (error) {
    return ctx.app.emit("error", new Error(ERROR_TOKEN), ctx);
  }
};

module.exports = {
  verifyAuth,
  verifySSL,
};
